package com.aierkeji.b2c.service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aierkeji.b2c.dao.jpa.AkjAlipayLifeSnapDao;
import com.aierkeji.b2c.dao.jpa.AkjAlipayOrderDao;
import com.aierkeji.b2c.dao.jpa.AkjProductDao;
import com.aierkeji.b2c.entity.AkjAlipayOrder;
import com.aierkeji.b2c.entity.snapshot.AkjAlipayLifeSnap;
import com.aierkeji.b2c.entity.vo.AlipayConfigVo;
import com.aierkeji.b2c.utils.AppConfig;
import com.aierkeji.b2c.utils.DateTimeUtils;
import com.aierkeji.b2c.utils.NumberUtils;
import com.aierkeji.b2c.utils.ResultMapHelper;
import com.aierkeji.b2c.utils.StringUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundAuthOperationDetailQueryModel;
import com.alipay.api.domain.AlipayFundAuthOrderAppFreezeModel;
import com.alipay.api.domain.AlipayFundAuthOrderUnfreezeModel;
import com.alipay.api.domain.AlipayTradeFastpayRefundQueryModel;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayFundAuthOperationDetailQueryRequest;
import com.alipay.api.request.AlipayFundAuthOrderAppFreezeRequest;
import com.alipay.api.request.AlipayFundAuthOrderUnfreezeRequest;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayFundAuthOperationDetailQueryResponse;
import com.alipay.api.response.AlipayFundAuthOrderAppFreezeResponse;
import com.alipay.api.response.AlipayFundAuthOrderUnfreezeResponse;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;

@Service
public class AlipayService {
	private final Logger log = LogManager.getLogger(getClass());

	@Autowired
	AkjAlipayOrderDao akjAlipayOrderDao;
	
	@Autowired
	AkjProductDao akjProductDao;
	
	
	@Autowired
	private AkjAlipayLifeSnapDao akjAlipayLifeSnapDao;
	
	private  final String succesCode = "success"; 
	private  final String failureCode = "fails"; 
	
	/**
	 * 预授权冻结接口
	 * @return 
	 * 
	 */
	
	public   Map<String,Object> fundAuthOrderAppFreeze(AlipayConfigVo alipayConfigVo,String title,String amount) {
		Map<String,Object> result = new HashMap<>();
		
//		 alipayConfigVo = new AlipayConfigVo();
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE);		
		AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
		AlipayFundAuthOrderAppFreezeModel model = new AlipayFundAuthOrderAppFreezeModel();
	    model.setOrderTitle(title);
	    String outOrderNo =  "oon"+StringUtils.getDate()+StringUtils.getTime()+StringUtils.getRandomStringByLength(6);
	    String outRequestNo =  "orn"+StringUtils.getDate()+StringUtils.getTime()+StringUtils.getRandomStringByLength(6);	    
	    model.setOutOrderNo(outOrderNo);//替换为实际订单号
	    model.setOutRequestNo(outRequestNo);//替换为实际请求单号，保证每次请求都是唯一的
	    model.setPayeeUserId(alipayConfigVo.PID);//payee_user_id,Payee_logon_id不能同时为空
	    model.setProductCode("PRE_AUTH_ONLINE");//PRE_AUTH_ONLINE为固定值，不要替换
	    String amount2 = NumberUtils.NumberMovePointLeft(amount,2);
	    model.setAmount(amount2);
	    //需要支持信用授权，该字段必传
	    model.setExtraParam("{\"category\":\"RENT_SHARABLE_CHARGERS\"}"); //outStoreAlias将在用户端信用守护、支付信息、账单详情页展示
	    //选填字段，指定支付渠道
	    //model.setEnablePayChannels("[{\"payChannelType\":\"PCREDIT_PAY\"},{\"payChannelType\":\"MONEY_FUND\"},{\"payChannelType\":\"CREDITZHIMA\"}]");
	    request.setBizModel(model);	   	    
	    AlipayFundAuthOrderAppFreezeResponse response = null;
		try {
			response = alipayClient.sdkExecute(request);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			log.error("",e);
		}		
		if(response.isSuccess()){
			AkjAlipayOrder aa  = new AkjAlipayOrder();
			aa.setOutOrderNo(outOrderNo);//'商户授权资金订单号',
			aa.setOutRequestNo(outRequestNo);//'商户本次资金操作的请求流水号',
			aa.setCreatTime(DateTimeUtils.getCurrentTime());//'创建时间',
			aa.setAmount(amount);//'冻结的金额',
			aa.setProductCode("PRE_AUTH_ONLINE");//product_code
			aa.setInPayId(alipayConfigVo.getPID());//'收款方的支付宝唯一用户号',
			akjAlipayOrderDao.save(aa);
			log.info("调用成功");
			String bodyStr = response.getBody();
//			log.info("bodyStr::" + bodyStr);
			result.put("url", bodyStr);
			result.put("id", aa.getId());
			result.put("data",aa);
			return result;
		} else {
			log.info("调用失败:{},:{},:{},:{}",response.getCode(),response.getMsg(),response.getSubCode(),response.getSubMsg());
		}
//		result.put("url", "");
//		result.put("id", "");
		return null;
	}
	
	/**
	 * 资金授权操作查询
	 */
	@Transactional
	public AkjAlipayOrder fundAuthQuery(AlipayConfigVo alipayConfigVo,String tid)  {
		AkjAlipayOrder aa  = akjAlipayOrderDao.findById(tid).get();
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE);
		AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
	    AlipayFundAuthOperationDetailQueryModel model = new AlipayFundAuthOperationDetailQueryModel();
	    model.setOutOrderNo(aa.getOutOrderNo()); //商户的授权资金订单号，与支付宝的授权资金订单号不能同时为空
	    model.setOutRequestNo(aa.getOutRequestNo());//商户的授权资金操作流水号，与支付宝的授权资金操作流水号不能同时为空，该值为冻结或解冻是的outRequestNo
	    request.setBizModel(model);
	    AlipayFundAuthOperationDetailQueryResponse response = null;
	    try {
			response = alipayClient.execute(request);
			log.info(response);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			log.error("",e);
		}
	    if("dev".equals(AppConfig.getProperty("envType"))) {
	    	
	    	log.info("调用成功");
			//资金操作流水的状态，目前支持： INIT：初始 	SUCCESS：成功 	CLOSED：关闭
			String status ="SUCCESS";
			//预授权类型，目前支持 CREDIT_AUTH(信用预授权); 
			String preAuthType = "CREDIT_AUTH";
			//付款方支付宝账号（Email或手机号），仅作展示使用，默认会加“*”号处理
			String payerLogonId = "test";
			//付款方支付宝账号对应的支付宝唯一用户号
			String buyerId = "test";
			//支付宝资金授权订单号
			String authNo = "test";
			
			//支付宝资金操作流水号
			String operationId = "test";
			Date date = new Date();//支付宝账务处理成功时间，			
			//log.info("bodyStr::" + bodyStr);
			aa.setFreezeStatus(status);//资金操作流水的状态， 目前支持： /INIT：初始/SUCCESS：成功 /CLOSED：关闭
			aa.setFreezeType(preAuthType);////预授权类型，目前支持 CREDIT_AUTH(信用预授权); 
			aa.setFreezeTime(new Timestamp(date.getTime()));//支付宝账务处理成功时间，
			aa.setAuthNo(authNo);//支付宝资金授权订单号
			aa.setOperationId(operationId);//支付宝资金操作流水号
			aa.setBuyerId(buyerId);////付款方
			aa.setPayerLogonId(payerLogonId);////付款方
	    	akjAlipayOrderDao.save(aa);
	    	return aa;
		}else if(response!=null&&response.isSuccess()){	    	
	    	log.info("调用成功");
			//资金操作流水的状态，目前支持： INIT：初始 	SUCCESS：成功 	CLOSED：关闭
			String status = response.getStatus();
			if(!"SUCCESS".equals(status)) {
				return null;
			}
			//预授权类型，目前支持 CREDIT_AUTH(信用预授权); 
			String preAuthType = response.getPreAuthType();
			//付款方支付宝账号（Email或手机号），仅作展示使用，默认会加“*”号处理
			String payerLogonId = response.getPayerLogonId();
			//付款方支付宝账号对应的支付宝唯一用户号
			String buyerId = response.getPayerUserId();
			//支付宝资金授权订单号
			String authNo = response.getAuthNo();
			
			//支付宝资金操作流水号
			String operationId = response.getOperationId();
			Date date = response.getGmtTrans();//支付宝账务处理成功时间，			
			//log.info("bodyStr::" + bodyStr);
			aa.setFreezeStatus(status);//资金操作流水的状态， 目前支持： /INIT：初始/SUCCESS：成功 /CLOSED：关闭
			aa.setFreezeType(preAuthType);////预授权类型，目前支持 CREDIT_AUTH(信用预授权); 
			aa.setFreezeTime(new Timestamp(date.getTime()));//支付宝账务处理成功时间，
			aa.setAuthNo(authNo);//支付宝资金授权订单号
			aa.setOperationId(operationId);//支付宝资金操作流水号
			aa.setBuyerId(buyerId);////付款方
			aa.setPayerLogonId(payerLogonId);////付款方
	    	akjAlipayOrderDao.save(aa);
	    	return aa;
		} else {
			log.info("调用失败");
		}
		return null;
	}
	
	public Map<String,Object> onlyFundAuthQuery(AlipayConfigVo alipayConfigVo,String tid)  {
	    Map<String,Object> result = new HashMap<>();
	    result.put("code", failureCode);
		AkjAlipayOrder aa  = akjAlipayOrderDao.findById(tid).get();
		if(aa==null) {
			log.info("AkjAlipayOrder is null:{}",tid);
			result.put("msg", "error id");
			return result;
		}
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE);
		AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
	    AlipayFundAuthOperationDetailQueryModel model = new AlipayFundAuthOperationDetailQueryModel();
	    model.setOutOrderNo(aa.getOutOrderNo()); //商户的授权资金订单号，与支付宝的授权资金订单号不能同时为空
	    model.setOutRequestNo(aa.getOutRequestNo());//商户的授权资金操作流水号，与支付宝的授权资金操作流水号不能同时为空，该值为冻结或解冻是的outRequestNo
	    request.setBizModel(model);
	    AlipayFundAuthOperationDetailQueryResponse response = null;
	    try {
			response = alipayClient.execute(request);
			log.info(response);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			log.error("",e);
		}
	    if(response!=null){	    	
	    	if(response.isSuccess()) {
		    	log.info("调用成功");
		    	result.put("code", succesCode);
		    	result.put("data", response.getStatus());
	    	}else {
	    		log.info("response failure tid:{}",tid);
				result.put("msg", response.getMsg());

	    	}
	    	
		} else {
			log.info("调用失败");
			result.put("msg", "response is null");

		}
		return result;
	}
	
	
	
	/**
	 * 通过使用auth_code换取接口access_token及用户userId
	 * 入参:lifeId,code
	 * 返回:userId,alipayUserId
	 */

	public Map<String, Object>  getUserId(String lifeId,String code) {
	
		AkjAlipayLifeSnap akjAlipayLife =akjAlipayLifeSnapDao.findById(lifeId).get();
		AlipayConfigVo alipayConfigVo = AlipayConfigVo.builder(akjAlipayLife);
		//返回的结果集
		Map<String,Object> result = new HashMap<>();
		result.put("userId", "");
	    result.put("alipayUserId", "");
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE);
		AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
		request.setCode( code);
		request.setGrantType("authorization_code");
		try {
		    AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
		    result.put("userId", oauthTokenResponse.getUserId());
		    result.put("alipayUserId", oauthTokenResponse.getAlipayUserId());
		    log.info("getUserId.result:{}",result);
		} catch (AlipayApiException e) {
		    //处理异常
			log.error("",e);
		}
		
		return result;
	}
	
	/**
	 * 资金授权解冻_对外入口处理
	 */
	
	public Map<String,Object> fundAuthOrderUnFreeze_in(Map<String,Object> params)  {
		String lifeId = (String)params.get("lifeId");
		AkjAlipayLifeSnap akjAlipayLife =akjAlipayLifeSnapDao.findById(lifeId).get();
		AlipayConfigVo configVo = AlipayConfigVo.builder(akjAlipayLife);
		String outOrderNo =  (String)params.get("outOrderNo"); 
		return fundAuthOrderUnFreeze(configVo,outOrderNo);
	}
	
	/**
	 * 资金授权解冻
	 */
	
	public Map<String, Object> fundAuthOrderUnFreeze(AlipayConfigVo alipayConfigVo,String outOrderNo)  {
		//返回的结果集
		Map<String,Object> result = new HashMap<>();
		if(alipayConfigVo.getTermination()) {
			log.info("termination",alipayConfigVo.getTermination() );
			result.put("code", succesCode);
			return result;
		}
		// 查出当前数据库支付宝订单对象
		AkjAlipayOrder aa  = akjAlipayOrderDao.findByOutOrderNo(outOrderNo);
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE);
		AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();
	    AlipayFundAuthOrderUnfreezeModel model = new AlipayFundAuthOrderUnfreezeModel();
	    model.setAuthNo(aa.getAuthNo()); // 支付宝资金授权订单号，在授权冻结成功时返回需要入库保存
	    model.setOutRequestNo(aa.getOutRequestNo());//同一商户每次不同的资金操作请求，商户请求流水号不能重复,且与冻结流水号不同
	    //String  amount2 = "你好,解冻"+NumberUtils.NumberMovePointLeft(aa.getAmount(),2)+"元";
	    String  amount2 = "解冻-支付宝预授权解冻完成";
	    model.setAmount(NumberUtils.NumberMovePointLeft(aa.getAmount(),2)); // 本次操作解冻的金额，单位为：元（人民币），精确到小数点后两位
	    model.setRemark(amount2); // 商户对本次解冻操作的附言描述，长度不超过100个字母或50个汉字 
	    //选填字段，信用授权订单，针对信用全免订单，传入该值完结信用订单，形成芝麻履约记录
	    model.setExtraParam("{\"unfreezeBizInfo\":\"{\\\"bizComplete\\\":\\\"true\\\"}\"}");      
	    request.setBizModel(model);
	    try {
			AlipayFundAuthOrderUnfreezeResponse response = alipayClient.execute(request);
			 if(response.isSuccess()){	    	
					log.info("调用成功");						
					aa.setUnfreezeRemark(amount2);
					aa.setUnfreezeStatus(response.getStatus());//资金操作流水的状态，目前支持： INIT：初始 	SUCCESS：成功 	CLOSED：关闭				
					Date date = response.getGmtTrans();//授权资金解冻成功时间，格式：YYYY-MM-DD HH:MM:SS		
					aa.setUnfreezeTime(new Timestamp(date.getTime()));
					//aa.setOperationId(operationId);//支付宝资金操作流水号
			    	akjAlipayOrderDao.save(aa);
			    	result.put("code", succesCode);
			    	return result;
				} else {
					log.info("调用失败:{},:{},:{},:{}",response.getCode(),response.getMsg(),response.getSubCode(),response.getSubMsg());
				}
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			log.error("",e);
		}
	    result.put("code", failureCode);
	    return result;
	}
	
	
	/**
	 * 授权转支付_对外入口处理
	 */
	
	public Map<String,Object> tradePay_in(Map<String,Object> params)  {
		String lifeId = (String)params.get("lifeId");
		AkjAlipayLifeSnap akjAlipayLife =akjAlipayLifeSnapDao.findById(lifeId).get();
		AlipayConfigVo configVo = AlipayConfigVo.builder(akjAlipayLife);
		String outOrderNo =  (String)params.get("outOrderNo"); 
		return tradePay(configVo,outOrderNo);
	}
	
	/**
	 * 授权转支付
	 */

	public Map<String, Object> tradePay(AlipayConfigVo alipayConfigVo ,String outOrderNo)  {
		//返回的结果集
		Map<String,Object> result = new HashMap<>();
		if(alipayConfigVo.getTermination()) {
			log.info("termination",alipayConfigVo.getTermination() );
			result.put("code", succesCode);
			return result;
		}
		// 查出当前数据库支付宝订单对象
		AkjAlipayOrder aa  = akjAlipayOrderDao.findByOutOrderNo(outOrderNo);
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE); 
	    AlipayTradePayRequest request = new AlipayTradePayRequest();	    
	    AlipayTradePayModel model = new AlipayTradePayModel();
	    model.setOutTradeNo(aa.getOutOrderNo()); // 预授权转支付商户订单号，为新的商户交易流水号；如果重试发起扣款，商户订单号不要变；
	    model.setProductCode("PRE_AUTH_ONLINE"); // 固定值PRE_AUTH_ONLINE
	    model.setAuthNo(aa.getAuthNo()); // 填写预授权冻结交易号//预授权号
	    model.setSubject("支付宝预授权完成支付"); // 解冻转支付标题，用于展示在支付宝账单中
	    model.setTotalAmount(NumberUtils.NumberMovePointLeft(aa.getAmount(),2)); // 结算支付金额
	    model.setSellerId(aa.getInPayId()); // 填写卖家支付宝账户pid
	    model.setBuyerId(aa.getBuyerId()); // 填写预授权用户uid，通过预授权冻结接口返回的payer_user_id字段获取
	    model.setAuthConfirmMode("COMPLETE");//必须使用COMPLETE,传入该值用户剩余金额会自动解冻
	    request.setBizModel(model);
	  //  request.setNotifyUrl(notify_url);//异步通知地址，必填，该接口只通过该参数进行异步通知	    
	    AlipayTradePayResponse response = null;
		try {
			response = alipayClient.execute(request);
			
		} catch (AlipayApiException e) {
			log.error("",e);
	        result.put("code", failureCode);
			return result;
		}
	    if(response.isSuccess()){
	        //response.getGmtPayment();//交易支付时间
	        if("10000".equals(response.getCode())) {
	        	Date date =  response.getGmtPayment();
	        	aa.setTradeTime(new Timestamp(date.getTime()));//'支付时间',
	        	aa.setTradeStatus("success");//'支付交易状态',
	        	aa.setTradeNo(response.getTradeNo());//'支付宝交易号',
	        	aa.setOutTradeNo(response.getOutTradeNo());////'支付宝流水号',
	        	akjAlipayOrderDao.save(aa);
	        	 result.put("code", succesCode);
	        }
	        
	    } else {
			log.info("调用失败:{},:{},:{},:{}",response.getCode(),response.getMsg(),response.getSubCode(),response.getSubMsg());
	        result.put("code", failureCode);
	    }
	    return result;
	}
	
	
	/**
	 * 交易查询
	 * 名称：alipay.trade.query
	 *类型：服务端接口
		功能：通过该接口可以查询单笔明细的详细信息。
	 */
	public Map<String,Object> tradeQuery(AlipayConfigVo alipayConfigVo ,String tid)  {
		//返回的结果集
		Map<String,Object> result = new HashMap<>();
		// 查出当前数据库支付宝订单对象
		AkjAlipayOrder aa  = akjAlipayOrderDao.findById(tid).get();
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE); 
	    AlipayTradeQueryModel model = new AlipayTradeQueryModel();
	    model.setOutTradeNo(aa.getOutTradeNo());
	    AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
	    request.setBizModel(model);
	    AlipayTradeQueryResponse response = null;
	    try {
			 response = alipayClient.execute(request);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			log.error("",e);
	        result.put("code", failureCode);
			return result;
		}
	    if(response.isSuccess()){
        	//'支付交易状态',交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
        	aa.setTradeStatus(response.getTradeStatus());
        	akjAlipayOrderDao.save(aa);
        	result.put("code", succesCode);
	    } else {
	    	result.put("code", failureCode);
			log.info("调用失败:{},:{},:{},:{}",response.getCode(),response.getMsg(),response.getSubCode(),response.getSubMsg());
	    }
	    
	    return result;
	}
	
	
	/**
	 * 授权转支付_对外入口处理
	 */
	
	public Map<String,Object> tradeRefund_in(Map<String,Object> params)  {
		String lifeId = (String)params.get("lifeId");
		AkjAlipayLifeSnap akjAlipayLife =akjAlipayLifeSnapDao.findById(lifeId).get();
		AlipayConfigVo configVo = AlipayConfigVo.builder(akjAlipayLife);
		String outOrderNo =  (String)params.get("outOrderNo"); 
		return tradeRefund(configVo,outOrderNo);
	}
	
	/**交易退款
	 * 名称：alipay.trade.refund
	 */
	public Map<String, Object> tradeRefund(AlipayConfigVo alipayConfigVo ,String outOrderNo)  {
		//返回的结果集
		Map<String,Object> result = new HashMap<>();
		if(alipayConfigVo.getTermination()) {
			log.info("termination",alipayConfigVo.getTermination() );
			result.put("code", succesCode);
			return result;
		}
				
		// 查出当前数据库支付宝订单对象
		AkjAlipayOrder aa  = akjAlipayOrderDao.findByOutOrderNo(outOrderNo);
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE); 
		AlipayTradeRefundModel model = new AlipayTradeRefundModel();
	    model.setOutTradeNo(aa.getOutTradeNo()); //与预授权转支付商户订单号相同，代表对该笔交易退款
	    model.setOutRequestNo(aa.getOutRequestNo());//标识一次退款请求，同一笔交易多次退款需要保证唯一
	    String amount2 = NumberUtils.NumberMovePointLeft(aa.getAmount(),2);
	    model.setRefundAmount(amount2);
	    model.setRefundReason("支付宝预授权退款");    
	    AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
	    request.setBizModel(model);
	    AlipayTradeRefundResponse response = null;
	    try {
			response = alipayClient.execute(request);
		} catch (AlipayApiException e) {
			log.error("",e);
	        result.put("code", failureCode);
			return result;
		}
	    if(response.isSuccess()){
	    	aa.setRefundAmount(aa.getAmount());//'退款金额',
	    	aa.setRefundTime(DateTimeUtils.getCurrentTime());//'退款时间',
	    	aa.setRefundStatus("goRefund");//退款状态',执行款中
        	akjAlipayOrderDao.save(aa);
        	result.put("code", succesCode);
	    } else {
	        result.put("code", failureCode);
			log.info("调用失败:{},:{},:{},:{}",response.getCode(),response.getMsg(),response.getSubCode(),response.getSubMsg());
	    }
	    
	    return result;
	}
	
	
	/**
	 * 名称：alipay.trade.fastpay.refund.query
		类型：服务端接口
		功能：商户可使用该接口查询自已通过alipay.trade.refund提交的退款请求是否执行成功。
	 */
	public Map<String,Object> tradeFastpayRefundQuery(AlipayConfigVo alipayConfigVo ,String tid)  {
		//返回的结果集
		Map<String,Object> result = new HashMap<>();
		// 查出当前数据库支付宝订单对象
		AkjAlipayOrder aa  = akjAlipayOrderDao.findById(tid).get();
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE); 
		AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
	    model.setOutRequestNo(aa.getOutRequestNo());
	    model.setTradeNo(aa.getTradeNo());
	    AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
	    request.setBizModel(model);
	    AlipayTradeFastpayRefundQueryResponse response = null;
		try {
			response = alipayClient.execute(request);
		} catch (AlipayApiException e) {
			log.error("",e);
	        result.put("code", failureCode);
			return result;
		}
	    if(response.isSuccess()){
	        log.info("调用成功");
	       if(response.getRefundStatus() == null ||"REFUND_SUCCESS".equals(response.getRefundStatus())) {
	    	   aa.setRefundStatus("REFUND_SUCCESS");//refund_status为空或为REFUND_SUCCESS，则代表退款成功，
	    	   akjAlipayOrderDao.save(aa);
	    	   result.put("code", succesCode);
	       };
	       
	    } else {
		    result.put("code", failureCode);
			log.info("调用失败:{},:{},:{},:{}",response.getCode(),response.getMsg(),response.getSubCode(),response.getSubMsg());
	    }
	    
	    return result;
	}

	public AlipayFundAuthOperationDetailQueryResponse test(AlipayConfigVo alipayConfigVo, String tid) {
		AkjAlipayOrder aa  = akjAlipayOrderDao.findById(tid).get();
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE);
		AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
	    AlipayFundAuthOperationDetailQueryModel model = new AlipayFundAuthOperationDetailQueryModel();
	    model.setOutOrderNo(aa.getOutOrderNo()); //商户的授权资金订单号，与支付宝的授权资金订单号不能同时为空
	    model.setOutRequestNo(aa.getOutRequestNo());//商户的授权资金操作流水号，与支付宝的授权资金操作流水号不能同时为空，该值为冻结或解冻是的outRequestNo
	    request.setBizModel(model);
	    AlipayFundAuthOperationDetailQueryResponse response = null;
	    try {
			response = alipayClient.execute(request);
			log.info(response);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			log.error("",e);
		}
		return response;
	}
	
	public static void main(String[] args) {
		AlipayConfigVo alipayConfigVo = new AlipayConfigVo();
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigVo.URL, alipayConfigVo.APPID,
				alipayConfigVo.RSA_PRIVATE_KEY, alipayConfigVo.FORMAT, alipayConfigVo.CHARSET, alipayConfigVo.ALIPAY_PUBLIC_KEY,
				alipayConfigVo.SIGNTYPE);
		AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
	    AlipayFundAuthOperationDetailQueryModel model = new AlipayFundAuthOperationDetailQueryModel();
	    model.setOutOrderNo("oon201908051826057bjr8c"); //商户的授权资金订单号，与支付宝的授权资金订单号不能同时为空
	    model.setOutRequestNo("orn20190805182605074w6r");//商户的授权资金操作流水号，与支付宝的授权资金操作流水号不能同时为空，该值为冻结或解冻是的outRequestNo
	    request.setBizModel(model);
	    AlipayFundAuthOperationDetailQueryResponse response = null;
	    try {
			response = alipayClient.execute(request);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    if(response.isSuccess()){	    	
			//资金操作流水的状态，目前支持： INIT：初始 	SUCCESS：成功 	CLOSED：关闭
			String status = response.getStatus();
			//预授权类型，目前支持 CREDIT_AUTH(信用预授权); 
			String preAuthType = response.getPreAuthType();
			//付款方支付宝账号（Email或手机号），仅作展示使用，默认会加“*”号处理
			String payerLogonId = response.getPayerLogonId();
			//付款方支付宝账号对应的支付宝唯一用户号
			String buyerId = response.getPayerUserId();
			//支付宝资金授权订单号
			String authNo = response.getAuthNo();
			
			//支付宝资金操作流水号
			String operationId = response.getOperationId();
			Date date = response.getGmtTrans();//支付宝账务处理成功时间，			
			//log.info("bodyStr::" + bodyStr);
//			aa.setFreezeStatus(status);//资金操作流水的状态， 目前支持： /INIT：初始/SUCCESS：成功 /CLOSED：关闭
//			aa.setFreezeType(preAuthType);////预授权类型，目前支持 CREDIT_AUTH(信用预授权); 
//			aa.setFreezeTime(new Timestamp(date.getTime()));//支付宝账务处理成功时间，
//			aa.setAuthNo(authNo);//支付宝资金授权订单号
//			aa.setOperationId(operationId);//支付宝资金操作流水号
//			aa.setBuyerId(buyerId);////付款方
//			aa.setPayerLogonId(payerLogonId);////付款方
			System.out.println(status);
			System.out.println(authNo);
		} else {
			System.out.println(1111);
		}
	    
	    
//	    AlipayFundAuthOrderUnfreezeRequest request2 = new AlipayFundAuthOrderUnfreezeRequest();
//	    AlipayFundAuthOrderUnfreezeModel model2 = new AlipayFundAuthOrderUnfreezeModel();
//	    model2.setAuthNo("2019071610002001880569543918"); // 支付宝资金授权订单号，在授权冻结成功时返回需要入库保存
//	    model2.setOutRequestNo("orn20190716211414hmtqaq");//同一商户每次不同的资金操作请求，商户请求流水号不能重复,且与冻结流水号不同
//	    //String  amount2 = "你好,解冻"+NumberUtils.NumberMovePointLeft(aa.getAmount(),2)+"元";
//	    String  amount2 = "解冻-支付宝预授权解冻完成";
//	    model2.setAmount(NumberUtils.NumberMovePointLeft(5900,2)); // 本次操作解冻的金额，单位为：元（人民币），精确到小数点后两位
//	    model2.setRemark(amount2); // 商户对本次解冻操作的附言描述，长度不超过100个字母或50个汉字 
//	    //选填字段，信用授权订单，针对信用全免订单，传入该值完结信用订单，形成芝麻履约记录
//	    model2.setExtraParam("{\"unfreezeBizInfo\":\"{\\\"bizComplete\\\":\\\"true\\\"}\"}");      
//	    request2.setBizModel(model2);
//	    try {
//			AlipayFundAuthOrderUnfreezeResponse response2 = alipayClient.execute(request2);
//			 if(response2.isSuccess()){	    	
//					System.out.println(1);
//				} else {
//					System.out.println(2);
//				}
//		} catch (AlipayApiException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}
	
	
	
}
